package com.cac.demo.controller.compressedFiles;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cac.demo.newCode.interfaceLog.service.InterfaceLogService;
import com.cac.demo.newCode.sorting.utils.IPUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping("/compressedFiles")
@Slf4j
public class CompressedFilesEditor {

    @Autowired
    private Environment environment;
    @Resource
    private InterfaceLogService interfaceLogService;

    //文件发送
    @PostMapping("/fileSend")
    public void fileSend(Object list,String zipFilePath, String cemopUrl,String description) {
        String url = environment.getProperty("cemopUrl.proxy");
        System.out.println("=========================fileSend文件发送地址=============================："+url);
        //获取ip
        String IP = IPUtils.getIP();
        String URI = IPUtils.getRequestURI();
        JSONObject sendData = new JSONObject();
        Map<String, Object> BDataMap = new HashMap<>();
        String bKey = IdUtil.simpleUUID();
        sendData.put("bKey",bKey);
        sendData.put("filePath","");//生成的压缩包路径
        sendData.put("fileUrl", zipFilePath);
        sendData.put("auditMap", "");
        BDataMap.put("fileSendUrl",cemopUrl);//Cemop接口路径
        BDataMap.put("fileSendMsgUrl", "");
        sendData.put("BData", BDataMap);
        System.out.println("=====================Cemop两网传输调用代理服务器传递参数========================："+sendData.toString());
        if("false".equals(environment.getProperty("pathProperty.debug"))){
            String result= com.cac.demo.util.HttpUtil.post(url, sendData.toJSONString());
            System.out.println("=====================Cemop两网传输调用代理服务器返回参数========================："+result);
            interfaceLogService.saveInterfaceLog(description,cemopUrl,list,result,IP,URI,bKey);
        }
        interfaceLogService.saveInterfaceLog(description,cemopUrl,list,"测试",IP,URI,bKey);
    }
    //接收文件发送
    @Async
    @PostMapping("/fileSendhutool")
    public void fileSendhutool(String zipFilePath, String cemopUrl) {
        String url = environment.getProperty("cemopUrl.proxy");
        System.out.println("=========================fileSendhutool文件发送地址=============================："+url);

        JSONObject sendData = new JSONObject();
        Map<String, Object> BDataMap = new HashMap<>();
        String bKey = IdUtil.simpleUUID();
        sendData.put("bKey",bKey);
//			sendData.put("filePath",dirPath+zipFileName);//生成的压缩包路径
        sendData.put("filePath","");//生成的压缩包路径
        sendData.put("fileUrl", zipFilePath);
        sendData.put("auditMap", "");
        BDataMap.put("fileSendUrl",cemopUrl);//Cemop接口路径
        BDataMap.put("fileSendMsgUrl", "");
        sendData.put("BData", BDataMap);
        System.out.println("=====================两网传输调用代理服务器传递参数========================："+sendData.toString());
        String result= HttpUtil.post(url, sendData.toJSONString());
        System.out.println("=====================Cemop两网传输调用代理服务器返回参数========================："+result);
    }
    //下载.zip文件并解析出json数据
//    @GetMapping("/parseJsonFromZip")
    public String parseJsonFromZip(String path) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // Create request entity with necessary headers (if needed)
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");  // Set appropriate headers if required
            HttpEntity<String> requestEntity = new HttpEntity<>(path, headers);
            RestTemplate restTemplate = new RestTemplate();
            System.out.println("==============请求路径=====================requestEntity="+requestEntity);
            // Perform POST request to download the file
            byte[] zipBytes = restTemplate.exchange(
                    path,
                    HttpMethod.GET,
                    requestEntity,
                    byte[].class
            ).getBody();

            if (zipBytes == null) {
                System.out.println("==============找不到ZIP文件=====================");
                return "找不到ZIP文件";
            }
            //获取保存地址
            String saveDir = environment.getProperty("cemopUrl.saveDirurl");
            String fileName = "file" + new Random().nextInt(1000) + ".zip";
            // 保存ZIP文件到服务器
            File saveFile = new File(saveDir + File.separator + fileName);
            try (FileOutputStream outputStream = new FileOutputStream(saveFile)) {
                outputStream.write(zipBytes);
            }

            // Unzip the file and parse JSON content
            try (InputStream is = new ByteArrayInputStream(zipBytes);
                 ZipInputStream zis = new ZipInputStream(is)) {

                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    if (entry.getName().endsWith(".txt")) {
                        // Read and parse JSON from the .txt file
                        String json = IOUtils.toString(zis, "UTF-8");

                        JsonNode jsonNode = objectMapper.readTree(json);

                        return jsonNode.toPrettyString();
                    }
                }
            }

            return "找不到.txt文件";
        } catch (IOException e) {
            e.printStackTrace();
            return "处理文件时出错";
        }
    }

    @PostMapping("/processZip")
    public String processZip(@RequestParam String urlString){
        try {
            // 创建临时文件
            Path tempDir = Files.createTempDirectory("unzipped");
            Path tempFile = Files.createTempFile("downloaded", ".zip");

            // 下载.zip文件
            try (InputStream in = new URL(urlString).openStream()) {
                Files.copy(in, tempFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            }

            // 解压.zip文件并读取.txt文件中的JSON数据
            String jsonData = null;
            try (ZipInputStream zis = new ZipInputStream(new FileInputStream(tempFile.toFile()))) {
                ZipEntry zipEntry;
                while ((zipEntry = zis.getNextEntry()) != null) {
                    if (zipEntry.getName().endsWith(".txt")) {
                        Path newFile = tempDir.resolve(zipEntry.getName());
                        try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
                            byte[] buffer = new byte[1024];
                            int len;
                            while ((len = zis.read(buffer)) > 0) {
                                fos.write(buffer, 0, len);
                            }
                        }

                        // 读取.txt文件中的JSON数据
                        byte[] bytes = Files.readAllBytes(newFile);
                        jsonData = new String(bytes);
                        break;
                    }
                }
            }

            // 删除临时文件和目录
            Files.deleteIfExists(tempFile);
            Files.walk(tempDir)
                    .sorted((a, b) -> b.compareTo(a))
                    .forEach(p -> {
                        try {
                            Files.delete(p);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

            if (jsonData == null) {
                throw new FileNotFoundException("No .txt file found in the zip archive");
            }

            // 返回读取的JSON数据
            return jsonData;
        }
        catch (IOException e) {
            e.printStackTrace();
            return "Error processing the request: " + e.getMessage();
        }
    }
    //生成zip文件并存储到本地，生成下载url
    public String generateZip(@RequestBody String jsonData) {
        System.out.println("=====================生成zip文件并存储到本地，生成下载url========================");
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        String LINUX_FIXED_DIR =environment.getProperty("cemopUrl.linuxFixedDir");
        String format = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);

        File folder = new File(LINUX_FIXED_DIR + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名，避免文件重名
        String filename = fileId();
        String txtFileName = filename + ".txt";
        String zipFileName = filename + ".zip";

        try {
            // 将JSON数据保存为.txt文件
            Path txtFilePath = Paths.get(folder.getAbsolutePath(), txtFileName);
            Files.write(txtFilePath, jsonData.getBytes());

            // 压缩.txt文件为.zip文件
            Path zipFilePath = Paths.get(folder.getAbsolutePath(), zipFileName);
            try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath.toFile()))) {
                ZipEntry zipEntry = new ZipEntry(txtFilePath.getFileName().toString());
                zos.putNextEntry(zipEntry);
                Files.copy(txtFilePath, zos);
                zos.closeEntry();
            }
            System.out.println("=====================zip文件保存成功========================");

            // 删除.txt文件
            Files.deleteIfExists(txtFilePath);

            String getfileurl = environment.getProperty("cemopUrl.getfileurl");
            // 返回上传文件的访问路径
            String fileDownloadUri = getfileurl + format + "/" + zipFileName;
            System.out.println("=====================生成下载url========================"+fileDownloadUri);
            return fileDownloadUri;
        } catch (IOException e) {
            return "Error occurred: " + e.getMessage();
        }
    }


    //代理可通过下载链接下载zip文件
    @GetMapping("/downloadZip")
    public ResponseEntity<byte[]> downloadZip(String path) throws IOException {
        Path zipPath = Paths.get(path);
        byte[] zipContent = Files.readAllBytes(zipPath);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.zip");

        return new ResponseEntity<>(zipContent, headers, HttpStatus.OK);
    }
    /**
     * @throws
     * @Title: fileReceiveTest
     * @Description: 解析压缩文件（.txt）
     * @param: @param BData
     * @param: @param files
     * @param: @return
     */
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }

        try {
            // 将文件解压
            try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(file.getBytes()))) {
                ZipEntry entry;
                while ((entry = zipInputStream.getNextEntry()) != null) {
                    if (!entry.isDirectory() && entry.getName().endsWith(".txt")) {
                        // 读取文本文件内容
                        String content = StreamUtils.copyToString(zipInputStream, StandardCharsets.UTF_8);

                        // 解析JSON内容
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode jsonNode = objectMapper.readTree(content);

                        // 输出解析后的JSON
                        return jsonNode.toPrettyString();
                    }
                }
            }
        } catch (IOException e) {
            return "文件解析失败";
        }

        return "未找到.txt文件";
    }
    //随机生成8位字符
    private String fileId() {
        // 定义字符集
        String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        // 创建随机数生成器
        Random random = new Random();
        // 生成8位随机字符
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(charSet.length());
            char randomChar = charSet.charAt(index);
            stringBuilder.append(randomChar);
        }
        // 打印生成的随机字符串
        String randomString = stringBuilder.toString();
        return randomString;
    }
}